export type Channel = {
    appId: string
    avatar: string
    companyId: number
    createTime: string
    id: number
    identity: string
    mobile: string
    modifyTime: string
    nickName: string
    openId: string
    unReadCount: number
    userIds: string
} & AnyContent

export type AnyMessage = {
    companyId: number,
    createTime: string,
    id: number,
    identity: string,
    isReply: number,
    nickName: string,
    openId: string,
    replyErrorMsg: string,
    timeMillis: number,
    villageId: number,
    avatar: string
} & AnyContent

export interface MessageContent {
    content: any
    msgType: string
}

export interface TextContent extends MessageContent {
    content: {
        content: string
    }
    msgType: 'text'
}

export interface VoiceContent extends MessageContent {
    content: {
        content: string
    }
    msgType: 'voice'
}

export interface ImageContent extends MessageContent {
    content: {
        content: string
    }
    msgType: 'image'
}

export interface VideoContent extends MessageContent {
    content: {
        content: string
    }
    msgType: 'video'
}

export interface LocationContent extends MessageContent {
    msgType: 'location'
}

export interface ShortVideoContent extends MessageContent {
    msgType: 'shortvideo'
}

export type AnyContent = TextContent | VoiceContent | ImageContent | VideoContent | LocationContent | ShortVideoContent
export type MessageType = AnyContent['msgType']


import http from 'src/framework/network/http'
import avatarGuest from './assets/avatar-guest.svg'
import avatarWorker from './assets/avatar-worker.svg'

export async function fetchMessages(params: { openId: string, appId: string, timeInMilleSeconds?: number }) {
    const worker = Promise.resolve({
        avatar: avatarWorker
    })
    const msgs = await http.post<AnyMessage[]>('/msg/wx/listItem', params)
    msgs.forEach(async msg => {
        msg.content = JSON.parse(msg.content)
        if (msg.isReply) {
            msg.avatar = (await worker).avatar
        } else {
            msg.avatar = msg.avatar ?? avatarGuest
        }
    })
    return msgs
}

export async function fetchChannels(params: {t: number}) {
    const channels = await http.get<Channel[]>('/msg/wx/list', params)
    channels.forEach(channel => {
        channel.avatar = channel.avatar || avatarGuest
        channel.content = JSON.parse(channel.content)
    })
    return channels
}